<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\func\Lib;
use app\common\func\Tools;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 分润设置
 *
 * @icon fa fa-circle-o
 */
class Profit extends Backend
{

    protected $searchFields = 'title';

    /**
     * Profit模型对象
     * @var \app\common\model\Profit
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Profit;
        $this->view->assign("mainTypeList", $this->model->getMainTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $query = $this->model
                    ->with(['product']);
            if(!$this->auth->isSuperAdmin()){
                $company = $this->auth->getCompany();
                $query->where(["profit.main_type" => 1 ,"profit.main_id" => $company->id]);
            }else{
                $query->where(["main_type" => 0 ,"main_id" => 0]);
            }
            $query->where(["profit.status"=>1]);

            $list = $query->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','main_type','main_id','title','status','create_time']);
                $row->visible(['product']);
				$row->getRelation('product')->visible(['name']);
                $main = Tools::getMainInfo($row->main_type,$row->main_id);
                $row->main_type = $main['type'];
                $row->main_id = $main['name'];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->view->assign('super', !$this->auth->isSuperAdmin() ? true : false);
            if(!$this->auth->isSuperAdmin()){
                $list = Lib::getPolicyRelationList(1,$this->auth->getCompany()->id);
                $companyIds = Lib::getCompanyProducts(1,$this->auth->getCompany()->id);
                $this->view->assign('ids', implode(",",$companyIds));
                $this->view->assign("list",$list);
                $this->view->assign("is_admin",false);
            }else{
                $this->view->assign("is_admin",true);
            }
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if(!$this->auth->isSuperAdmin()){
                $company = $this->auth->getCompany();
                if(!$company){
                    $this->error(__('未绑定机构，请联系上级绑定！'));
                }
                $params['main_type'] = 1;
                $params['main_id'] = $company->id;
                $params['super_profit'] = $params['policy'];
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if(!$this->auth->isSuperAdmin()){
                $companyIds = Lib::getCompanyProducts(1,$this->auth->getCompany()->id);
                $this->view->assign('ids', implode(",",$companyIds));
            }
            $this->view->assign('super', !$this->auth->isSuperAdmin() ? true : false);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function list(){
        if($this->auth->isSuperAdmin()){
            $productId = $this->request->post('product_id');
            $product = Lib::getProductById($productId);

            $rateList = Lib::getRateListByIds($product->rate_ids);
            $transactionTypeList = Lib::getTransactionTypeBYIds($product->transaction_type_ids);
            $cardTypeList = Tools::getCardTypeObj();
            $channelList = Lib::getChannelByIds($product->channel_ids);
        }else{
            $profitId = $this->request->post('profit_id');
            $profit = Lib::getProfitById($profitId);

            $rateList = Lib::getRateListByIds($profit->rate_ids);
            $transactionTypeList = Lib::getTransactionTypeBYIds($profit->transaction_type_ids);
            $cardTypeList = Tools::getCardTypeObj($profit->card_type);
            $channelList = Lib::getChannelByIds($profit->channel_ids);
        }

        $this->success("", null, [
            "rate" => $rateList,
            "transaction_type" => $transactionTypeList,
            "card_type" => $cardTypeList,
            "channels" => $channelList,
        ]);
    }

    public function setting($ids = null){
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if($this->auth->isSuperAdmin()){
            $mainType = 0;
            $mainId = 0;
        }else{
            $company = $this->auth->getCompany();
            $mainType = $company->pid == 0 ? 0 :1;
            $mainId = $company->pid == 0 ? 0 :$company->id;
        }

        if (false === $this->request->isPost()) {
            $data = [];
            foreach (Tools::getCardTypeList(explode(",",$row->card_type)) as $key => $val){
                foreach (Lib::getTransactionList(explode(",",$row->transaction_type_ids)) as $k => $v){
                    foreach (Lib::getRateList(explode(",",$row->rate_ids)) as $k1 => $v1){
                        foreach (Lib::getChannelByIds($row->channel_ids) as $k2 => $v2){
                            $profit = Lib::getProfitDetailsByParams($row->id,$key,$v->id,$v1->id,$v2->id);
                            if($profit){
                                $profitVal = $profit->profit_rate;
                            }else{
                                $profitVal = "";
                            }

                            if(!$this->auth->isSuperAdmin()){
                                $obj = Lib::getProfitRateByParams($row->super_profit,$key,$v->id,$v1->id,$v2->id);
                                if($obj){
                                    $max = $obj["profit_rate"];
                                }else{
                                    $max = 0;
                                }
                            }else{
                                $max = 0;
                            }

                            $data[] = [
                                "card" => $key,
                                "card_text" => Tools::$cardType[$key],
                                "tran" => $v->id,
                                "tran_text" => $v->name,
                                "rate" => $v1->id,
                                "rate_text" => $v1->name,
                                "channel" => $v2->id,
                                "channel_text" => $v2->name,
                                "profit" => $profitVal,
                                "max" => $max,
                            ];
                        }
                    }
                }
            }

            $this->view->assign('data', $data);
            return $this->view->fetch();
        }

        $card = $this->request->post('card/a');
        $tran = $this->request->post('tran/a');
        $rate = $this->request->post('rate/a');
        $channel = $this->request->post('channel/a');
        $profit = $this->request->post('profit/a');

        for ($i = 0;$i < count($profit);$i++){
            $detail = Lib::getProfitDetailsByParams($row->id,$card[$i],$tran[$i],$rate[$i],$channel[$i]);
            if($detail){
                if($detail->profit_rate != $profit[$i]){
                    $detail->profit_rate = $profit[$i];
                    $detail->save();
                }else{
                    continue;
                }
            }else{
                $details = new \app\common\model\ProfitDetails();
                $details->profit_id = $row->id;
                $details->card_type = $card[$i];
                $details->transaction_type_id = $tran[$i];
                $details->rate_id = $rate[$i];
                $details->channel_id = $channel[$i];
                $details->profit_rate = $profit[$i];
                $details->save();
            }
        }

        $this->success("设置成功！");
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $policyList = Lib::getPolicyBySetting("profit",$ids);

                if(count($policyList) > 0){
                    $this->error("已绑定政策，不可删除！");
                }
                $item->status = 2;
                if($item->save()){
                    $count += 1;
                }
//                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    public function ajax(){
        $id = $this->request->post("id");
        $profit = Lib::getProfitById($id);
        $this->success("","",$profit);
    }

}
